import { defineStore } from 'pinia'
import { reqCategoryTree } from '@/api/category'

export interface Category {
  catId: number
  name: string
  parentCid: number
  catLevel: number
  showStatus: number
  sort: number
  icon: string | null
  productUnit: string | null
  productCount: number
  children?: Category[]
}

export interface CategoryState {
  categoryList: Category[]
  loading: boolean
}

export const useCategoryStore = defineStore('category', {
  state: (): CategoryState => ({
    categoryList: [],
    loading: false,
  }),

  getters: {
    // 获取一级分类
    firstLevelCategories: (state) => {
      return state.categoryList
    },

    // 根据父级ID获取子分类
    getChildrenByParentId: (state) => (parentId: number) => {
      const findChildren = (categories: Category[]): Category[] => {
        let result: Category[] = []
        for (const category of categories) {
          if (category.catId === parentId && category.children) {
            return category.children
          }
          if (category.children) {
            const found = findChildren(category.children)
            if (found.length > 0) {
              result = found
              break
            }
          }
        }
        return result
      }
      return findChildren(state.categoryList)
    },
  },

  actions: {
    // 获取分类树数据
    async fetchCategoryTree() {
      this.loading = true
      try {
        const response = await reqCategoryTree()
        this.categoryList = response.data || []
      } catch (error) {
        console.error('获取分类数据失败:', error)
        this.categoryList = []
      } finally {
        this.loading = false
      }
    },

    // 根据分类ID获取分类信息
    getCategoryById(catId: number): Category | undefined {
      const findCategory = (categories: Category[]): Category | undefined => {
        for (const category of categories) {
          if (category.catId === catId) {
            return category
          }
          if (category.children) {
            const found = findCategory(category.children)
            if (found) return found
          }
        }
        return undefined
      }
      return findCategory(this.categoryList)
    },
  },
})
